﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.Business.Entitys.Dto.QmsBusiMessageboard;
using SHZY.Business.Entitys;
using SHZY.Business.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Entitys.Entity;

namespace SHZY.Business;

/// <summary>
/// 业务实现：留言模块.
/// </summary>
[ApiDescriptionSettings(Tag = "Business", Name = "Messageboard", Order = 200)]
[Route("api/Business/[controller]")]
public class QmsBusiMessageboardService : IQmsBusiMessageboardService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBusiMessageboardEntity> _repository;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBusiMessageboardService"/>类型的新实例.
    /// </summary>
    public QmsBusiMessageboardService(
        ISqlSugarRepository<QmsBusiMessageboardEntity> qmsBusiMessageboardRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBusiMessageboardRepository;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取留言模块列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBusiMessageboardListQueryInput input)
    {
        var data = await _repository.Context.Queryable<QmsBusiMessageboardEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.SendUserId == b.Id))
            .Where(a => a.ParentId.Equals(input.parentId) && a.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.Content.Contains(input.keyword))
            .OrderBy(a => a.SendTime,input.sort=="asc"? OrderByType.Asc: OrderByType.Desc)
            .Select((a, b) => new QmsBusiMessageboardListOutput
            {
                id = a.Id,
                parentId = a.ParentId,
                type = a.Type,
                sendUserId = a.SendUserId,
                realName = b.RealName,
                headIcon = SqlFunc.MergeString("/api/File/Image/userAvatar/", SqlFunc.IsNull(b.HeadIcon, "001.png")),
                sendTime = a.SendTime,
                content = a.Content,
                contentType = a.ContentType,
            }).ToPagedListAsync(input.currentPage, input.pageSize);
        data.list = data.list.OrderBy(x => x.sendTime);
        return PageResult<QmsBusiMessageboardListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建留言模块.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBusiMessageboardCrInput input)
    {
        var entity = input.Adapt<QmsBusiMessageboardEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 删除留言模块.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Deleteable<QmsBusiMessageboardEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
    }
}